package com.junjie.base.redis;

/**
 * @Author Jun jie Yi
 * @Date 2022/3/9 16:21
 */
import com.junjie.base.tool.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {

    private static JedisPool jedisPool = null;

    private static Integer redis_db = null;

    public static void main(String[] args) {
        //ip地址，端口号
        Jedis jedis = cli_pool();
        jedis.set("key", "first Java connect!");
        String value = jedis.get("key");
        System.out.println(value);

        RedisManager redisManager = new RedisManager();
        redisManager.set("key", "设置的值");
        String key = redisManager.get("key");
        System.out.println(key);
    }

    /**
     * 单个连接
     *
     * @param host
     * @param port
     * @return
     */
    public static Jedis cli_single(String host, int port) {
        try {
            return new Jedis(host, port);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 连接池
     *
     * @return
     */
    public synchronized static Jedis cli_pool() {
        //redis_db如果没有指定就赋值
        if (jedisPool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            // 最大连接数
            String setMaxTotal = PropertiesUtil.getProperty("redis_maxTotal");
            if (setMaxTotal != null) {
                config.setMaxTotal(Integer.parseInt(setMaxTotal));
            }
            // 最大连接空闲数
            String setMaxIdle = PropertiesUtil.getProperty("redis_maxIdle");
            if (setMaxTotal != null) {
                config.setMaxIdle(Integer.parseInt(setMaxIdle));
            }
            jedisPool = new JedisPool(
                    config,
                    PropertiesUtil.getProperty("redis_host"),
                    Integer.parseInt(PropertiesUtil.getProperty("redis_port"))
            );
            Jedis jedis = jedisPool.getResource();
            return setJedisParams(jedis);
        }

        Jedis jedis = jedisPool.getResource();
        return setJedisParams(jedis);
    }

    private static Jedis setJedisParams(Jedis jedis) {
        String redis_db = PropertiesUtil.getProperty("redis_db");
        String redis_auth = PropertiesUtil.getProperty("redis_auth");
        //一定要先认证，顺序不可变
        if (redis_auth != null) {
            jedis.auth(redis_auth);
        }
        if (redis_db != null) {
            jedis.select(Integer.parseInt(redis_db));
        }
        return jedis;
    }

}

